package net.dntuan.training.mvc.controller;

import java.util.List;

import net.dntuan.training.mvc.domain.City;
import net.dntuan.training.mvc.manager.CityManager;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

@Controller
@RequestMapping(value = "/city")
public class CityController {

    @Autowired
    private CityManager cityManager;

    @RequestMapping(value = { "", "/list" })
    public String list(Model model) {
        List<City> cities = cityManager.findAll();
        model.addAttribute("cities", cities);
        return "list";
    }

    @RequestMapping(value = "/delete")
    public String delete(@RequestParam(required = true) Long id) {
        cityManager.delete(id);
        return "redirect:list.html";
    }

    @RequestMapping(value = "/create")
    public String preCreate(Model model) {
        City city = new City();
        model.addAttribute("city", city);
        return "new";
    }

    @RequestMapping(value = "/save")
    public String save(Model model, City city) {
        System.out.println(city.getName());
        System.out.println(city.getDistrict());
        System.out.println(city.getPopulation());

        // TODO use a select box to allow users to select a country
        city.setCountryCode("VNM");

        cityManager.save(city);
        return "redirect:list.html";
    }

    @RequestMapping(value = "/edit")
    public String preEdit(Model model, @RequestParam(required = true) Long id) {
        City city = cityManager.findOne(id);
        model.addAttribute("city", city);
        return "edit";
    }

    @RequestMapping(value = "update")
    public String update(Model model, City city) {
        // TODO validate city before updating

        cityManager.update(city);
        return "redirect:list.html";
    }
}
